<template>
  <div>
    <div class="title">零售开单</div>
    <div style="margin-top: 20px;">
      <el-space>
        <div style="height: 30px;font-size: 18px;color: #515A6E;">日期：</div>
        <div style="height: 30px;font-size: 16px;color: #515A6E;">
          <JPicker disabled size="default" v-model="billDate" />
        </div>
        <div style="height: 30px;font-size: 18px;color: #515A6E;margin-left: 50px;">客户：</div>
        <div style="height: 30px;font-size: 16px;color: #515A6E;border-bottom: 1px solid rgba(0,0,0,0.2);min-width: 300px;">
          {{ buName }}
        </div>
<!--        <lbtn type="text" @click="hist">历史</lbtn>-->
        <lbtn type="text" @click="help">帮助</lbtn>
<!--                <el-button @click="doSearch">查询</el-button>-->
      </el-space>
    </div>
    <div style="margin-top: 20px;">
      <el-card  shadow="never" style="height: calc(100vh - 130px);" body-style="padding: 10px 0px;">
        <template #header>
          <div style="display: flex;">
            <div style="flex: 1;display: flex;">
              <el-space>
                <div style="margin-right: 50px;">
                  商品列表(可扫描条码)
                </div>
                <lbtn icon="plus" type="success" @click="addGood">加商品</lbtn>
              </el-space>

            </div>
            <div style="font-size: 20px;font-weight: bold;color: #515A6E;padding-top: 10px;border-bottom: 1px solid rgba(0,0,0,0.3);margin-right: 50px;padding-right: 10px;">
              零售金额￥：<span style="color: #c45656;">{{totalAmount}}</span>
            </div>
<!--            <div style="font-size: 20px;font-weight: bold;color: #515A6E;padding-top: 10px;border-bottom: 1px solid rgba(0,0,0,0.3);margin-right: 50px;padding-right: 10px;">-->
<!--             <el-space>-->
<!--               <span>优惠金额￥：</span>-->
<!--               <span style="color: #c45656;"><ltext v-model="disAmount" :width="100" /></span>-->
<!--             </el-space>-->
<!--            </div>-->
<!--            <div style="font-size: 20px;font-weight: bold;color: #515A6E;padding-top: 10px;border-bottom: 1px solid rgba(0,0,0,0.3);margin-right: 50px;padding-right: 10px;">-->
<!--              收款金额￥：<span style="color: #c45656;">{{amount}}</span>-->
<!--            </div>-->
            <div>
              <lbtn type="primary" size="medium" @click="confirm">保存并审核</lbtn>
            </div>
            <div style="margin-left: 30px;">
              <!--              <lbtn   size="medium" @click="clear">清空</lbtn>-->
            </div>
          </div>
        </template>
        <t-grid ref="tgridRef"  size="large" v-if="buId" :data-list="backList" :fields="columns" @editClosed="editClose" @cellClick="cellClick" />
        <el-empty v-if="!buId" description="扫描商品条码"></el-empty>
      </el-card>
    </div>
    <el-dialog v-model="showPop" title="修改单位" :z-index="9" :width="300">
      <tiny-select v-model="unit" placeholder="请选择" size="large" @change="changeUnit">
        <tiny-option v-for="(item, index) in units" :key="index" :label="item.name" :value="item.id"> </tiny-option>
      </tiny-select>
    </el-dialog>
    <el-dialog v-model="helpPop" draggable title="本页帮助说明">
      <el-image src="https://download.sanzhiyun.cn/web5/help/%E9%9B%B6%E5%94%AE.png"></el-image>
    </el-dialog>
    <popGood ref="popGoodRef" @moreSelect="moreSelect" />

  </div>
</template>
<script>
// 退包装物品
import tool from "@/utils/tool";
import bus from "@/store/bus.js";
import { Select, Option } from '@opentiny/vue'
import popGood from "@/lui/popGood.vue";

export default {
  name: "wrapperBack",
  components: {
    TinySelect: Select,
    TinyOption: Option,
    popGood
  },
  data () {
    return {
      billDate: tool.getDay(),
      locationId: null,
      locationName: null,
      buId: null,
      buName: '',
      address: '',
      code: '',
      backList: [],
      showPop: false,
      helpPop: false,
      columns:[
        {type: 'index', width: 50},
        {field: 'invName', title: '商品名称', width: 300,align: 'left'},
        {field: 'locationName', title: '仓库', width: 80},
        {field: 'specs', title: '规格', width: 80},
        {field: 'unit', title: '单位', width: 80},
        {field: 'qty', title: '数量', width: 110,editor: {component: 'input', autoselect: true,},sum: true,},
        {field: 'price', title: '单价', width: 110,editor: {component: 'input', autoselect: true}},
        {field: 'amount', title: '金额', width: 110,editor: {component: 'input', autoselect: true},sum: true},
        {field: 'remark', title: '备注', width: 110,editor: {component: 'input', autoselect: true}},
        {field: '', title: '操作', width: 100,align: 'center', btns:[{id: '删除',label: '删除',
          click: (row, rowIndex) => {
           this.backList.splice(rowIndex, 1)
          }}] },
      ],
      currentRow: {},
      units: [],
      unit: '',
      billId: '',
      disAmount: '0.00',
      arrearsReal: '0.00', // 原票据金额
    }
  },
  created () {
    bus.$on('scan-ret', this.scanRet)
    tool.post('deliver/getBuIdByName').then(ret => {
      if(ret.stat) {
        this.buId = ret.data.id
        this.buName = ret.data.name
        this.locationId = ret.data.locationId
        this.locationName = ret.data.locationName
      }
    })
  },
  unmounted () {
    bus.$off('scan-ret', this.scanRet)
  },
  computed: {
    totalAmount () {
      return tool.xe.toFixed(tool.xe.sum(this.backList, 'amount'),2)
    },
    tuiList () {
      return this.backList.filter(row => {
        return tool.xe.toNumber(row.qty) > 0
      })
    },
    amount () {
      return tool.xe.toFixed(tool.xe.subtract(this.totalAmount, this.disAmount), 2)
    }
  },
  methods: {
    help () {
      this.helpPop = true
    },
    hist () {
      this.helpPop = true
    },
    addGood () {
      this.$refs.popGoodRef.openChose('', this.buId)
    },
    moreSelect (list) {
      list.map(row => {
        row.invId = row.id
        row.invName = row.name
        row.locationName = this.locationName
        row.locationId = this.locationId
        row.specs = '1*'+row.spec
        row.qty = row.qty?row.qty:1
        this.backList.push({
          locationId: this.locationId,
          locationName: this.locationName,
          invId: row.id,
          invName: row.name,
          price: tool.xe.toFixed(row.price,2),
          unit: row.unit,
          unit1: row.unit1,
          unit2: row.unit2,
          specs: '1*'+row.spec,
          spec: row.spec,
          qty: row.qty?row.qty:1,
          amount: tool.xe.toFixed(tool.xe.multiply(row.qty?row.qty:1, row.price),2)
        })
      })
      console.log(list)
    },
    doSearch () {
      let code = '6926378912360'
      this.scanRet({code})
    },
    cellClick (cell) {
      if(cell.column.property === 'unit') {
        this.showPop = true
        this.currentRow = cell.row
        this.unit = cell.row.unit
        this.units = []
        this.units.push({id: cell.row.unit1, name: cell.row.unit1})
        if(cell.row.unit2)
          this.units.push({id: cell.row.unit2, name: cell.row.unit2})
      }
    },
    changeUnit (val) {
      this.currentRow.unit = val
      this.showPop = false
    },
    scanRet ({ code }) {
      tool.post('deliver/getGoodByCode', {code}, true).then(ret => {
        if(ret.stat) {
          this.backList.push({
            locationId: this.locationId,
            locationName: this.locationName,
            invId: ret.data.id,
            invName: ret.data.name,
            price: tool.xe.toFixed(ret.data.price,2),
            unit: ret.data.unit,
            unit1: ret.data.unit1,
            unit2: ret.data.unit2,
            specs: '1*'+ret.data.spec,
            spec: ret.data.spec,
            qty: 1,
            amount: tool.xe.toFixed(1 * ret.data.price,2)
          })
        }
      })
    },
    getList () {
      tool.post('deliver/backList', {code: this.code}, true).then(ret => {
        if(ret.stat) {
          this.locationId = ret.data.locationId
          this.locationName = ret.data.locationName
          this.buId = ret.data.buId
          this.buName = ret.data.buName
          this.address = ret.data.address
          this.arrearsReal = tool.xe.toFixed(ret.data.arrearsReal,2)
          this.backList = ret.data.list
        }
      })
    },
    editClose (cell) {
      let row = cell.row
      let field = cell.column.property
      if(field === 'qty') {
        row.qty = Math.abs(tool.xe.toNumber(row.qty))
        row.amount = tool.xe.toFixed(tool.xe.multiply(row.qty, row.price), 2)
      }
      if(field === 'price') {
        row.price = tool.xe.toFixed(Math.abs(tool.xe.toNumber(row.price)),2)
        row.amount = tool.xe.toFixed(tool.xe.multiply(row.qty, row.price), 2)
      }
      if(field === 'amount') {
        row.amount = tool.xe.toFixed(Math.abs(tool.xe.toNumber(row.amount)),2)
        if(tool.xe.toNumber(row.qty)) {
          row.price = tool.xe.toFixed(tool.xe.divide(row.amount, row.qty), 2)
        }
        else {
          row.amount = 0
        }
      }
      this.$refs.tgridRef.updateFooter()
    },
    confirm () {
      this.backList.map(row => {
        row.calNum = row.spec
        if(row.unit === row.unit2) row.calNum = 1
        row.qty = tool.xe.toNumber(row.qty)
      })
      for (let i = 0; i < this.backList.length; i++) {
        if(!this.backList[i].qty) {
          return tool.err('数量不能为 0 ')
        }
        if(!this.backList[i].invId) {
          return tool.err('没有选择商品')
        }
        if(!this.backList[i].locationId) {
          return tool.err('没有选择仓库')
        }
      }
      let invoice = {
        buId: this.buId,
        buName: this.buName,
        billDate: this.billDate,
        transType: 150601,
        transTypeName: '销售单',
        billType: 'SALE',
        totalAmount: tool.xe.sum(this.backList, 'amount'),
        amount: tool.xe.sum(this.backList, 'amount'),
        arrears: tool.xe.sum(this.backList, 'amount'),
        orgin: 'ps',
        infos: this.backList
      }
      tool.post('bill/saveLs', invoice, true).then(ret => {
        if(ret.stat) {
          tool.post('bill/toAccounted', {transType: 150601,ids: [ret.data.id]}).then(ret => {
            if(ret.stat) {
              this.clear()
            }
          })
        }
      })
    },
    clear () {
      this.billDate =  tool.getDay()
      this.backList = []
    }
  }
}
</script>
<style scoped lang="scss">
.title {
  text-align: center;
  font-weight: bold;
  font-size: 22px;
  background-color: #01aaee;
  color: white;
  height: 40px;
  line-height: 40px;
}
</style>